Java 學習筆記 06 – 類別與物件 Part 1


Posted by vickyh1315 on 2024-04-18

結構化程式設計強調區塊跟流程,改善傳統程式 goto 嚴格跳轉的缺點與增加易讀性,底層的結構化程式設計分成循序(sequence)、選擇(selection)及重複(repetition)。

如果發生重複執行100次的情況呢?

程序導向設計

程序導向是另一種設計方法論,採取過程呼叫(或函式呼叫)的方式,以 Main Funtion 為進入點,底下發展許多子函式,並讓程式執行的任何時間點,都可以呼叫特定程式,或被呼叫,做到易讀性更高的流程控制。

public class RectangleCalculator {
  public static void main(String[] args) {
    int width = setWidth(10);
    int height = setHeight(20);
    System.out.println(calculateArea(width, height));
  }

  public int calculateArea(int width, int height) {
    return width * height;
  }

  public int setWidth(int width) {
    return width;
  }

  public int setHeight(int height) {
    return height;
  }
}

可以將結構化設計看成程序導向設計的子集,在已經結構化的程式,使用模組化,做到更高階段的控制流程。

有了結構、有了函式,然而程序導向設計從 Main Function 開始執行,中間呼叫的函數可能會修改到同個變數,導致其他函數或模組也會受到影響,造成函數跟資料的高度耦合。

物件導向設計

物件導向採取分散控制(Decentralized control)的做法,透過類別產生物件,物件自己去修改自己的細節,同時不會影響到別的物件,降低相互的耦合性。

程序導向跟物件導向更貼近設計方法,常把語言分類為程序導向語言有 FORTRAN、VB、C 等,物件導向語言有 Java、C#、C++、Ruby 等,但實際上物件導向語言也可以寫出程序導向風格,程序導向語言也可以寫出物件導向風格。

類別與物件

類別(class)與物件(Object)是物件導向的基礎,可以把兩者看作「模具與物品」,一個類別會定義好

  • 資料(data):希望呈現的數據,且具備可被更改的狀態(state)
  • 行為(actions):可以對自己執行什麼操作

再透過 new (構造函數 Constructor)創建一個或多個物件,使它變成具有狀態和行為的實體。

進一步解釋兩者的差別,

  • 類別可看成一種規格書,定義好資料跟操作行為,沒有實體的概念,相同類別不能重複。
  • 物件是類別依照規格創造出來的實體,狀態隨時會被改變(且理想情況只能用行為去改變),但架構與行為不變,可以建立相同物件。

以下例子,Airline 即類別,定義好物件需要具備的變數、方法,再透過 new 建立物件,也會被稱為實例(Instance)。

public class Airline {
  String name;
  String hubs;
  int fleetSize;
  int Employees;

  public Airline(String name, String hubs, int fleetSize, int Employees) {
    this.name = name;
    this.hubs = hubs;
    this.fleetSize = fleetSize;
    this.Employees = Employees;
  }

  public String getInfos() {
    return "name: " + name + " Hubs: " + Hubs + " FleetSize: " + fleetSize + " Employees: " + Employees;
  }
}

public class AirlineRunner {
  public static void main(String[] args) {
    Airline ca = new Airline("China Airline", "Taipei–Taoyuan", 83, 11400);
    Airline sa = new Airline("
    Starlux Airline", "Taoyuan", 22, 4086);
  }
}

以用法來看,物件跟實例相似,但觀察 Object-Oriented Software Engineering 對於實例的定義,更強調物件依類別建立的這道關係,以及實體的概念,大多數情境大家習慣用物件的說法,當需要強調有實體的時候就會用實例,但其實可以看做相同的。

Instance
An instanceis an object created from a class. The class describes the (behavior and information)structure of the instance, while the current state of the instance is defined by the operations performed on the instance.

小結

比較程序導向跟物件導向,程序導向強調的是關於過程與方法的思考;物件導向則嘗試用物件的角度,考慮它們包含的數據、狀態,及對這些物件可進行的操作。

類別定義資料屬性跟操作行為,並可以建立出一個或多個物件,降低程式耦合的機會。


#java







Related Posts

解決 git@github.com permission denied (publickey) fatal: Could not read from remote repository.

解決 git@github.com permission denied (publickey) fatal: Could not read from remote repository.

程式基礎 —— Javascript 動手做 Part2

程式基礎 —— Javascript 動手做 Part2

[解題] 簡易小題目

[解題] 簡易小題目


Comments